﻿using System;
using System.Windows.Forms;
using CloudShot.Core.Interfaces;
using CloudShot.Interfaces;
using CloudShot.Settings;
using CloudShot.Utils;

namespace CloudShot.Services
{
  internal sealed class ConfigurationService : IConfigurationService
  {
    #region Fields and Consts

    private const string DefaultAppSection = "CloudShot";
    private const string RecentShotsSection = "RecentShots";

    private readonly IConfiguration _appConfiguration = new JsonConfiguration(AppHelper.ConfigFile);
    private readonly IConfiguration _recentShotsConfiguration = new JsonConfiguration(AppHelper.RecentShotsFile);

    #endregion

    public IConfigurationSection GetAppConfiguration()
    {
      IConfigurationSection appConfigurationSection = _appConfiguration.GetConfigurationSection(DefaultAppSection);

      if (appConfigurationSection.GetAs<CloudShotSettings>() == null)
      {
        IConfiguration defaultConfiguration = new JsonConfiguration(AppHelper.DefaultConfig);
        IConfigurationSection section = defaultConfiguration.GetConfigurationSection(DefaultAppSection);
        var settings = section.GetOrCreateAs<CloudShotSettings>();

        appConfigurationSection.SaveAs(settings); 
      }

      return appConfigurationSection;
    }

    public IConfigurationSection GetRecentShotsConfiguration()
    {
      return _recentShotsConfiguration.GetConfigurationSection(RecentShotsSection);
    }

    public IConfigurationSection GetPluginConfiguration(Type pluginType)
    {
      return _appConfiguration.GetConfigurationSection(pluginType.Name);
    }

    public void SetAutomaticStartup(bool isStartWithComputer)
    {
#if !DEBUG
      RegistryUtils.SetStartup(Application.ProductName, isStartWithComputer);
#endif
    }
  }
}